// pages/square/list.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "关注", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    classArr: [{
      id: 0,
      name: '关注'
    }, {
      id: 1,
      name: '粉丝'
    }, {
      id: 2,
      name: '喜欢'
    }, {
      id: 3,
      name: '收藏'
    }],
    classId: 0,
    forumList: [],
    isHeightMode: false,
    listType: 0,
    gzList: [],
    fansList: [],
    likeList: [],
    forumList: [],
    is_nickAndHead: 0,
    openid: '',
    shareImg: '',
    shareTitle: '',
    isOne: 1,
    page: 1, //当前页数
    isLoadingEnd: 0, //0:数据未加载完 1:数据已加载完
    isloading: false,
    showCircle: true,
    headerUrl: '',
    classArr2: [{
      id: 0,
      name: '最新'
    }, {
      id: 1,
      name: '最多赞'
    }],
    classId2: 0, //1:最新 2：最热

    isHaveMore: true,
    userId: ''
  },

  chooseClass2(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    this.setData({
      classId2: id
    });

    //调用查询列表
    that.getListPageInfo(that.data.openid, id, that.data.classId, that.data.listType);
  },
  //点击圈子
  qz() {
    let that = this;
    that.setData({
      listType: 0,
      classId2: 0
    });
    that.getListPageInfo(that.data.openid, 0, that.data.classId, 0);
  },
  //点击麓家书
  ljs() {
    let that = this;
    that.setData({
      listType: 2,
      classId2: 0
    })
    that.getListPageInfo(that.data.openid, 0, that.data.classId, 2);
  },
  //点击悦攻略
  ygl() {
    let that = this;
    that.setData({
      listType: 3,
      classId2: 0
    })
    that.getListPageInfo(that.data.openid, 0, that.data.classId, 3);
  },
  //method
  //method
  hotCircleCilck: function (event) {
    var tapId = event.currentTarget.id;
    this.addHeaderUrl();
    wx.navigateTo({
      url: '/pages/marketing/yglDetail?id=' + tapId + "&pageFlag=3"
    })
  },
  //点击麓客局
  lkj() {
    let that = this;
    that.setData({
      listType: 1
    })
    that.getListPageInfo(that.data.openid, 0, that.data.classId, 1);
  },
  //点击家书
  goLjs(e) {
    var id = e.currentTarget.dataset.id;
    var url = e.currentTarget.dataset.url;
    var type = e.currentTarget.dataset.type;
    //添加回跳
    this.addHeaderUrl();
    //判断是跳转微信稿还是详情页
    if (type == 0) {
      //跳转详情页
      wx.navigateTo({
        url: '/pages/marketing/ljsDetail?id=' + id
      })
    } else {
      //跳转微信稿
      wx.navigateTo({
        url: '/pages/webView/webView?wx_url=' + url
      })
    }


  },

  //跳转至麓客局详情页
  goGameDetail(e) {
    var that = this;
    var row = e.currentTarget.dataset.index;
    var id = that.data.forumList[row].id;
    var gameUserId = that.data.forumList[row].userId;
    that.addHeaderUrl();
    //判断是否点击的是自己的组局
    if (gameUserId == that.data.userId) {
      //跳转自自己的组局
      wx.redirectTo({
        url: '/pages/square/myPart?id=' + id
      });
    } else {
      wx.redirectTo({
        url: '/pages/square/partDetail?id=' + id
      });
    }
  },

  //跳转至帖子详情
  goPostDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/commentDetail?id=' + id
    });
  },


  //跳转至标签页
  goDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    if (id == that.data.tid) {
      return;
    }
    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/talk?tid=' + id
    });
  },

  //点击头像跳转其他人的帖子
  goOtherDetail(e) {
    var that = this;
    var userId = e.currentTarget.dataset.userid;
    var openid = e.currentTarget.dataset.openid;
    //判断是否是自己的主页
    if (userId == this.data.userId) {
      //跳自己的主页
      that.addHeaderUrl();
      wx.redirectTo({
        url: '/pages/square/my'
      });
    } else {
      that.addHeaderUrl();
      //跳别人的主页
      wx.redirectTo({
        url: '/pages/square/ta?userId=' + userId + "&openid=" + openid
      });
    }
  },

  //攻略点赞
  helpGl(e) {
    var that = this;
    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZanGl.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].is_zan']: "1",
              ['forumList[' + index + '].zan_number']: parseInt(that.data.forumList[index].zan_number) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].is_zan']: "0",
              ['forumList[' + index + '].zan_number']: parseInt(that.data.forumList[index].zan_number) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //将回跳url写入缓存
  addHeaderUrl() {
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array) {
      if (this.data.headerUrl == headerUrlList[headerUrlList.length - 1]) {
        //与上一个回跳链接相同则不添加
        return;
      }
      headerUrlList.push(this.data.headerUrl);
      wx.setStorageSync('headerUrlList', headerUrlList);
    } else {
      headerUrlList = [];
      headerUrlList.push(this.data.headerUrl)
      wx.setStorageSync('headerUrlList', headerUrlList);
    }
  },

  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  //点击切换tab
  chooseClass(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let defaultData = that.data.defaultData;
    if (id == 0) {
      defaultData.title = "关注"
    }
    if (id == 1) {
      defaultData.title = "粉丝"
    }
    if (id == 2) {
      defaultData.title = "喜欢"
    }
    if (id == 3) {
      defaultData.title = "收藏"
    }
    this.setData({
      classId: id,
      defaultData,
      classId2: 0,
      listType: 0
    });

    //重新加载数据
    that.getListPageInfo(that.data.openid, 0, id, that.data.listType);
  },
  // 预览图片
  previewImage(e) {
    let {
      sources,
      index
    } = e.currentTarget.dataset
    sources.filter(i => {
      i.type = i.type == 2 ? 'video' : 'image'
      i.poster = i.imgUrl
    })
    console.log("sources:", sources)
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },
  // 视频加载完成，改变视频的宽高
  videometa2(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = 331;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },
  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    wx.getImageInfo({
      src: e.currentTarget.dataset.sources[0],
      success: function (res) {
        console.log(res.width, res.height); // 这里获取的宽高是正确的
        res.height >= res.width && this.setData({
          isHeightMode: true
        })
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },

  //关注或取消关注该用户
  addGz(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }


    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var taOpenid = e.currentTarget.dataset.openid;
    var taUserId = e.currentTarget.dataset.tauserid;
    var index = e.currentTarget.dataset.index;
    var flag = e.currentTarget.dataset.flag;
    var cate = e.currentTarget.dataset.cate;
    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addGz.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'taOpenid': taOpenid,
        'taUserId':taUserId,
        'flag': flag
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (cate == 'fans') {
            if (flag == 'add') {
              that.setData({
                ['fansList[' + index + '].is_gz']: 1
              });
            } else {
              that.setData({
                ['fansList[' + index + '].is_gz']: 0
              });
            }
          } else {
            if (flag == 'add') {
              that.setData({
                ['gzList[' + index + '].is_gz']: 1
              });
            } else {
              that.setData({
                ['gzList[' + index + '].is_gz']: 0
              });
            }
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //收藏
  collect(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addSc.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].collect.status']: "1",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].collect.status']: "0",
              ['forumList[' + index + '].collect.num']: parseInt(that.data.forumList[index].collect.num) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //点赞
  help(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZan.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.forumList[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['forumList[' + index + '].help.status']: "1",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) + 1
            })

          } else {
            that.setData({
              ['forumList[' + index + '].help.status']: "0",
              ['forumList[' + index + '].help.num']: parseInt(that.data.forumList[index].help.num) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  // 预览图片
  previewImage(e) {
    let {
      sources,
      index
    } = e.currentTarget.dataset
    sources.filter(i => {
      i.type = i.type == 2 ? 'video' : 'image'
      i.poster = i.imgUrl
    })
    console.log("sources:", sources)
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    let menuIndex = options.menuIndex;

    let defaultData = that.data.defaultData;
    if (menuIndex == 0) {
      defaultData.title = "关注"
    }
    if (menuIndex == 1) {
      defaultData.title = "粉丝"
    }
    if (menuIndex == 2) {
      defaultData.title = "喜欢"
    }
    if (menuIndex == 3) {
      defaultData.title = "收藏"
    }

    if (isNaN(menuIndex) == false) {
      that.setData({
        classId: parseInt(menuIndex),
        defaultData
      });
    }

    //赋值回跳本页的url
    that.setData({
      headerUrl: '/pages/square/list?menuIndex=' + menuIndex
    });
    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }



    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getListPageInfo(res.data.openid, 0, menuIndex, that.data.listType);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getListPageInfo(openid, 0, menuIndex, that.data.listType);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getListPageInfo(openid, sort, menuIndex, listType) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getListPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        menuIndex: menuIndex,
        sort: sort,
        listType: listType
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            forumList: res.data.forumList,
            is_nickAndHead: res.data.is_nickAndHead,
            isLoadingEnd: res.data.isLoadingEnd,
            gzList: res.data.gzList,
            fansList: res.data.fansList,
            likeList: res.data.likeList,
            userId:res.data.userId
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    var timeout = setTimeout(function () {
      that.setData({
        showCircle: false
      });
      clearTimeout(timeout)
    }, 100)

    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    });

    //判断是否删除了攻略帖子
    var delId = wx.getStorageSync('delGlId');
    if (delId > 0 && delId != undefined) {
      let list = that.data.forumList;
      let row = 0;
      for (var i = 0; i < list.length; i++) {
        if (list[i]['id'] == delId) {
          row = i;
          break;
        }
      }

      // 使用splice删除元素
      list.splice(row, 1);

      //重新整理列表数组
      that.setData({
        forumList: list
      });
      //清空缓存
      wx.setStorageSync('delGlId', 0);
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      showCircle: true
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})